package com.ccteam.fluidmusic.ui.artist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.doOnPreDraw
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentArtistDetailBinding
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.utils.generateContainerTransform
import com.ccteam.fluidmusic.view.bean.LoadMessage
import com.ccteam.fluidmusic.widget.AppBarStateChangeListener
import com.ccteam.model.artist.ArtistVO
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint
import jp.wasabeef.glide.transformations.BlurTransformation

@AndroidEntryPoint
class ArtistDetailFragment: Fragment() {

    private var _binding: FragmentArtistDetailBinding? = null
    private val binding get() = _binding!!

    private val screenWidth: Int by lazy {
        resources.displayMetrics.widthPixels
    }

    private val artistDetailViewModel: ArtistDetailViewModel by viewModels()
    private val args: ArtistDetailFragmentArgs by navArgs()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
        // 设置共享动画
        sharedElementEnterTransition = generateContainerTransform(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentArtistDetailBinding.inflate(inflater,container,false)
        // 设置AppbarLayout的高度（为屏幕宽度）
        binding.collapseToolbarArtistDetail.layoutParams.apply {
            height = screenWidth
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        postponeEnterTransition()
        view.doOnPreDraw {
            startPostponedEnterTransition()
        }

        binding.toolbarArtistDetail.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.appbarArtistDetail.addOnOffsetChangedListener(object: AppBarStateChangeListener(){
            override fun onOffsetChanged(appBarLayout: AppBarLayout) {
            }

            override fun onStateChanged(appBarLayout: AppBarLayout, state: Int) {
                // 当处于折叠状态时，我们将不显示的透明度变为0
                // 当重新展开时，再将其显示
                if(state == COLLAPSED){
                    binding.ivArtistPhoto.animate().alpha(0f).setDuration(175).start()
                } else {
                    binding.ivArtistPhoto.animate().alpha(1f).setDuration(175).start()
                }
            }

        })

        val adapter = ArtistDetailPagerAdapter(args.artistId,this)
        binding.viewpagerArtistDetail.adapter = adapter

        TabLayoutMediator(binding.tabArtistDetail,
            binding.viewpagerArtistDetail){ tab, position ->
            val text = when(position){
                0 -> getString(R.string.description_tab_songs)
                1 -> getString(R.string.description_tab_albums)
                else -> null
            }
            tab.text = text
        }.attach()

        binding.statusView.setRetryClickListener {
            artistDetailViewModel.refreshArtistInfo()
        }

        artistDetailViewModel.artistInfo.observe(viewLifecycleOwner, {
            it?.let {
                updateArtistInfo(it)
            }
        })

        artistDetailViewModel.loadMessage.observe(viewLifecycleOwner, {
            val visible = it !is LoadMessage.Loading
            binding.appbarArtistDetail.isVisible = visible
            binding.viewpagerArtistDetail.isVisible = visible

            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
            binding.statusView.changeToErrorStatus(null)
        })

        artistDetailViewModel.showAppbar.observe(viewLifecycleOwner, {
            binding.appbarArtistDetail.isVisible = it
        })

        binding.statusView.setRetryClickListener {
            artistDetailViewModel.refreshArtistInfo()
        }
    }

    private fun updateArtistInfo(artistVO: ArtistVO) = with(binding){
        Glide.with(ivArtistPhoto)
            .load(artistVO.imgUrl)
            .placeholder(R.drawable.img_default_album)
            .into(ivArtistPhoto)
        // 高斯模糊的图片，放在清晰图片上方，但图片大小不能太大，否则会导致高斯模糊效果不佳
        Glide.with(binding.ivArtistPhotoBlur)
            .load(artistVO.imgUrl)
            .placeholder(R.drawable.img_default_album)
            .override(100,100)
            .apply(RequestOptions.bitmapTransform(BlurTransformation(25)))
            .into(binding.ivArtistPhotoBlur)
        toolbarArtistDetail.title = artistVO.name
    }

    class ArtistDetailPagerAdapter(
        private val artistId: String,
        fragment: Fragment): FragmentStateAdapter(fragment){
        override fun getItemCount(): Int = 2

        override fun createFragment(position: Int): Fragment {
            return when(position){
                0 -> ArtistDetailMusicPagerFragment.newInstance(artistId)
                1 -> ArtistDetailAlbumPagerFragment.newInstance(artistId)
                else ->
                    throw IllegalArgumentException("错误的布局参数")
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}